<template>
	<view>
		<uni-list :border="true">
			<uni-swipe-action-item
				:right-options="options"
				@click="(e) => onClick(e, index)"
				@change="swipeChange($event, 0)"
				v-for="(item, index) in list"
				:key="index + JSON.stringify(item)"
			>
				<uni-list-chat
					@click="() => selectCategory(item)"
					:title="item.name"
					:avatar="item.image"
					clickable
					:note="'¥' + item.price"
					time=""
				></uni-list-chat>
			</uni-swipe-action-item>
		</uni-list>
		<uni-popup ref="inputDialog" type="dialog">
			<view class="form-container">
				<uni-forms
					:modelValue="formData"
					:rules="rules"
					ref="form"
					label-position="top"
				>
					<!-- <uni-forms-item label="上级分类" name="categoryId">
						<uni-data-picker
							placeholder="请选择上级分类"
							popup-title="请选择上级分类"
							:localdata="treeList"
							v-model="formData.categoryId"
							:map="{ text: 'name', value: 'id' }"
						>
						</uni-data-picker>
					</uni-forms-item> -->
					<uni-forms-item label="产品名" required name="name">
						<uni-easyinput
							type="text"
							v-model="formData.name"
							placeholder="请输入产品名"
						/>
					</uni-forms-item>
					<uni-forms-item label="产品售价" name="price">
						<uni-easyinput
							type="number"
							v-model="formData.price"
							placeholder="请输入产品售价"
						/>
					</uni-forms-item>
					<uni-forms-item label="产品进价" name="purchasePrice">
						<uni-easyinput
							type="number"
							v-model="formData.purchasePrice"
							placeholder="请输入产品进价"
						/>
					</uni-forms-item>
					<uni-forms-item label="供应商" name="supplier">
						<uni-easyinput
							type="text"
							v-model="formData.supplier"
							placeholder="请输入供应商"
						/>
					</uni-forms-item>
					<uni-forms-item label="产品图" name="image">
						<uni-file-picker
							limit="1"
							@select="select"
							:auto-upload="false"
							return-type="object"
							v-model="formData.image"
						></uni-file-picker>
					</uni-forms-item>
				<!-- 	<uni-forms-item label="备注" name="remark">
						<uni-easyinput
							type="textarea"
							v-model="formData.remark"
							placeholder="请输入备注"
						/>
					</uni-forms-item> -->
				</uni-forms>
				<button class="button" type="primary" @click="submit">保存</button>
			</view>
		</uni-popup>
	</view>
</template>
<script>
import { handleTree } from '@/utils/utils.js'
import { upload,download } from '@/api/category'
export default {
	data() {
		return {
			formData: {
				id: '',
				name: '',
				price: 0,
				image: [],
				categoryId: '',
				remark: '',
				purchasePrice:0,
				supplier:''
				
			},
			list: [],
			options: [
				{
					text: '复制',
					style: {
						backgroundColor: '#007aff'
					}
				},
				{
					text: '删除',
					style: {
						backgroundColor: '#dd524d'
					}
				}
			],
			rules: {
				name: {
					rules: [
						{
							required: true,
							errorMessage: '请输入产品名'
						}
					]
				}
			},
			filePath: ''
		}
	},
	onNavigationBarButtonTap: function (e) {
		console.log(e)
		// e的返回格式为json对象：{"text":"测试","index":0}
		switch (e.index) {
			case 0:
				this.formData = {
					id: '',
					name: '',
					price: 0,
					image: [],
					categoryId: '',
					remark: ''
				}
				this.$refs.inputDialog.open()
				break
			case 1:
			   var that = this;
			   download().then(res=>{
				   if(res.success){
					   const url = res.data;
					   console.log(url)
					   uni.downloadFile({
							url: url, //仅为示例，并非真实的资源
							success: (res) => {
								console.log('下载成功', res)
								const url = plus.io.convertLocalFileSystemURL(res.tempFilePath)
								plus.io.resolveLocalFileSystemURL(
									url,
									function (entry) {
										entry.file(function (file) {
											var reader = new plus.io.FileReader()
											reader.onloadend = function (e) {
												// 这里可以拿到文件内容
												console.log('文件内容：', JSON.parse(e.target.result))
												uni.setStorageSync(
													'category_list_key',
													e.target.result
												)
												uni.showToast({
													title: '导入成功',
													icon: 'success',
													duration: 2000
												})
												that.getData()
											}
											reader.readAsText(file, 'utf-8') // 也可以用 readAsDataURL、readAsBinaryString 等
										})
									},
									function (e) {
										console.log('resolveLocalFileSystemURL 失败', e)
									}
								)
							}
					   	})
				   }
			   })
		
								
				break
			case 2:
				const dataToSav1e = uni.getStorageSync('category_list_key')
				this.upload(dataToSav1e)
				break
		}
	},
	computed: {
		treeList() {
			const tree = handleTree(this.list)
			console.log(tree)
			return tree
		}
	},
	onLoad() {
		this.getData()
	},
	methods: {
	
	    upload(data){
			upload(data).then(res=>{
				if(res.success){
					uni.showToast({
					  title: '上传成功',
					  icon: 'none',
					  duration: 2000
					})
				}
			})
		},
	
		getData() {
			//uni.clearStorage("category_list_key")
			uni.getStorage({
				key: 'category_list_key',
				success: (res) => {
					console.log('获取数据成功', res)
					this.list = JSON.parse(res.data)
					console.log(this.list)
				},
				fail: (err) => {
					console.log('获取数据失败', err)
				}
			})
		},
		selectCategory(item) {
			console.log(item)
			this.formData = {
				...item,
				image: item.image
					? [
							{
								url: item.image,
								image: item.image,
								location: item.image,
								name: item.image
							}
					  ]
					: []
			}
			this.$refs.inputDialog.open()
		},
		swipeChange(e, index) {
			console.log('当前状态：' + e + '，下标：' + index)
		},
		onClick(e, index) {
			console.log(
				'点击了' +
					(e.position === 'left' ? '左侧' : '右侧') +
					e.content.text +
					'按钮'
			)
			if (e.content.text == '删除') {
				uni.showModal({
					title: '提示',
					content: '确认删除吗？',
					success: (res) => {
						if (res.confirm) {
							let arr = this.list
							arr.splice(index, 1)
							uni.setStorageSync('category_list_key', JSON.stringify(arr))
							this.getData()
						}
					}
				})
			} else if (e.content.text == '复制') {
				let arr = this.list
				let item = arr[index]
				console.log(item)
				arr.push({
					...item,
					id: new Date().getTime().toString(),
					name: item.name + '_副本'
				})
				uni.setStorageSync('category_list_key', JSON.stringify(arr))
				this.getData()
			}
		},
		submit() {
			uni.showLoading()
			this.$refs.form
				.validate()
				.then((res) => {
					uni.hideLoading()
					console.log('表单数据信息：', res, this.formData)
					let data = {
						id: this.formData.id || new Date().getTime().toString(),
						pid: this.formData.categoryId,
						categoryId: this.formData.categoryId,
						name: this.formData.name,
						price: this.formData.price,
						image:
							this.formData.image && this.formData.image.length
								? this.formData.image[0].url
								: '',
						remark: this.formData.remark,
						supplier: this.formData.supplier,
						purchasePrice : this.formData.purchasePrice
					}
	                // console.log("缓存里面的数据1",value)
					const value = uni.getStorageSync('category_list_key')
					console.log("缓存里面的数据",value)
					if (value) {
						let arr = JSON.parse(value);
						if (this.formData.id) {
						  // 查找匹配项的索引
						  const index = arr.findIndex(item => item.id === this.formData.id);
						  if (index !== -1) {
						    // 如果找到匹配项，直接替换（保持原位置）
						    arr[index] = data;  // 用新数据替换旧数据
						  } else {
						    // 如果没找到匹配项，添加到末尾（或你希望的其他位置）
						    arr.push(data);
						  }
						} else {
						  // 如果没有 id，直接添加到末尾
						  arr.push(data);
						}
						uni.setStorageSync('category_list_key', JSON.stringify(arr))
						this.$refs.inputDialog.close()
					} else {
						console.log("====")
						let arr = []
						arr.push(data)
						uni.setStorageSync('category_list_key', JSON.stringify(arr))
						this.$refs.inputDialog.close()
					}

					this.getData()
				})
				.catch((err) => {
					uni.hideLoading()
					console.log('表单错误信息：', err)
				})
		},
		select(res) {
			console.log('select', res)
			if (res.tempFiles) {
				let imageInfo = res.tempFiles[0]
				uni.saveFile({
					tempFilePath: imageInfo.image.location,
					success: (res) => {
						console.log('保存文件成功', res)
						const url = plus.io.convertLocalFileSystemURL(res.savedFilePath)
						this.formData.image = [
							{
								url: 'file://' + url,
								image: 'file://' + url,
								location: 'file://' + url,
								name: 'file://' + url
							}
						]
						console.log('保存文件成功', url)
					},
					fail: (err) => {
						console.log('保存文件失败', err)
					}
				})
			}
		}
	},

	onUnload() {}
}
</script>
<style scoped lang="scss">
.form-container {
	width: 90vw;
	background-color: white;
	border-radius: 20rpx;
	padding: 30rpx;
}
</style>
